package com.priusoft.api.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;

public class JwtUtil {

    private static String TOKEN_SECRET = "aqwe"; // 密钥
    private static long EXPIRE_TIME = 24*60*60*1000; // 过期时间 1天

    /**
     * 生成token
     * @param userid
     * @return
     */
    public static String createToken(String userid) {
        String token = "";

        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); // 算法对象

            // 设置头信息
            HashMap<String, Object> header = new HashMap<>();
            header.put("typ", "JWT"); // 加密类型是 JWT
            header.put("alg", "HS256"); // 算法是 HS256
            token = JWT.create()
                    .withHeader(header) // JWT添加header
                    .withClaim("username", userid) // 声明userid
                    .withExpiresAt(date) // 设置过期时间
                    .sign(algorithm); // 签名
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return token;
    }

    public static String checkToken(String token) {
        String result = null;
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); // 算法对象
            JWTVerifier verifier = JWT.require(algorithm).build(); // JWT验证器

            DecodedJWT jwt = verifier.verify(token);
            result = jwt.getClaim("username").asString();
        } catch (Exception e){
        }
        return result;
    }
}
